package 文件上传;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

// 线程任务类，执行上传任务
public class ServerRunnable implements Runnable {
    private Socket socket ;

    public ServerRunnable(Socket socket) {
        this.socket = socket;
    }

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try(
                InputStream inputStream = socket.getInputStream();  //根据 客户端 创建的字节输入流
                BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
                OutputStream outputStream =
                        new FileOutputStream(
//                                字节输出流,向目标地址 存储 客户端 上传的文件
//                                                        数字和字母 随机的字符串
                                Constant.TargetFile+ UUID.randomUUID().toString()+".jpg");
                BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream); //封装高级缓冲流
        ) {
            byte[] bytes = new byte[1024*64];
            int len ;
            while ((len = bufferedInputStream.read(bytes)) != -1) { // 读取客户端上传的文件
                bufferedOutputStream.write(bytes,0,len);    // 向服务器文件夹中存储读取客户端上传的文件
            }

            System.out.println("服务器接收数据完成");    // 控制台打印信息

            PrintStream printStream = new PrintStream(socket.getOutputStream());    //建立向客户端通信的打印流
            printStream.print("数据接收成功");    // 向客户端打印信息
            printStream.flush();    //刷新打印流数据

        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("上传失败"); // 控制台打印数据
        }
    }
}
